using Arch.EntityFrameworkCore.UnitOfWork;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using WebApi.context;
using WebApi.model;
using WebApi.respository;
using Common.dto;
using Microsoft.Extensions.Options;
using WebApi.filter;
using WebApi.service;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddDbContext<ToDoTaskContext>(option => {

    option.UseSqlServer("Server=(local);Integrated Security=SSPI;Initial Catalog=ToDoTask_api;TrustServerCertificate=true");

    option.UseLazyLoadingProxies();

    
    
}).AddUnitOfWork<ToDoTaskContext>()
.AddCustomRepository<ToDoTask,ToDoTaskRepository>()
.AddCustomRepository<Memo,MemoRepository>()
.AddCustomRepository<User, UserRepository>();


var config = new MapperConfiguration(cfg => cfg.CreateMap<User, UserDto>().ReverseMap());

IMapper mapper = config.CreateMapper();

builder.Services.AddSingleton<IMapper>(mapper);

/*
 必须使用 AddTransient() 才能启动成功
 使用 AddSingleton 则一直报错
 */
builder.Services.AddTransient<IUserService,UserService>();
builder.Services.AddTransient<IToDoTaskService,ToDoTaskService>();
//builder.Services.AddSingleton<IUserService, UserService>();

builder.Services.AddControllers(options =>
{
    options.Filters.Add<AuthorizationFilter>();
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

using (var scope = app.Services.CreateScope())
{
    var context = scope.ServiceProvider.GetRequiredService<ToDoTaskContext>();
    context.Database.EnsureCreated();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();


app.Run();
